package com.emm.yixun.system.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.jws.WebService;

import com.emm.yixun.common.model.enums.MerchantEnum;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.enums.ModelEnum;
import com.emm.yixun.basic.service.CompanyService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.ModelKeyService;
import com.emm.yixun.basic.service.SalesGroupService;
import com.emm.yixun.basic.service.SalesGroupUserService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.AgentListResDto;
import com.emm.yixun.common.app.QueryAgentListByCustomerPhoneReqDto;
import com.emm.yixun.common.app.servletentity.AgentRes;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.DataAuthorityEnums;
import com.emm.yixun.common.enums.ImageTypeEnum;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.Department;
import com.emm.yixun.common.model.SalesGroup;
import com.emm.yixun.common.model.SalesGroupUser;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.DepartmentDto;
import com.emm.yixun.common.model.dto.HrmDepartment;
import com.emm.yixun.common.model.dto.HrmResource;
import com.emm.yixun.common.model.dto.OaUserExcelDto;
import com.emm.yixun.common.model.dto.OrgOaDataVo;
import com.emm.yixun.common.model.dto.ResponseOrg;
import com.emm.yixun.common.model.dto.SalesGroupUserDto;
import com.emm.yixun.common.model.dto.SubCompany;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.SsoLoginEnum;
import com.emm.yixun.common.model.enums.UserStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.FileUploadPorxyUtil;
import com.emm.yixun.common.utils.PasswordUtil;
import com.emm.yixun.common.utils.SequencesGenerator;
import com.emm.yixun.system.service.DepartmentServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;

@Service("userServiceFacade")
@WebService(endpointInterface = "com.emm.yixun.system.service.UserServiceFacade")
public class UserServiceFacadeImpl implements UserServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserService service;
	@Autowired
	private ModelKeyService modelKeyService;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	private SalesGroupUserService salesGroupUserService;
	@Autowired
	private SalesGroupService salesGroupService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private DepartmentServiceFacade departmentServiceFacade;

	@Override
	public Response<User> login(Long merchantId, String account, String password) {
		// 验证参数
		Response<User> response = new Response<User>();
		try {
			if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("登陆"));
				return response;
			}
			UserDto userDto = new UserDto();
			if (null != merchantId) {
				userDto.setMerchantId(merchantId);
			}
			String password2 = "";
			String originPassword = password;
			// 判断是否SSO过来的账户
			// SSO_、_LOGIN标识,在WebSite的Const类中
			if (account.indexOf(SsoLoginEnum.PREFIX.getNo()) >= 0
					&& account.indexOf(SsoLoginEnum.SUFFIX.getNo()) >= 0) {
				int beginIndex = SsoLoginEnum.PREFIX.getNo().length();
				int endIndex = account.indexOf(SsoLoginEnum.SUFFIX.getNo());
				account = account.substring(beginIndex, endIndex);
				logger.info("SSO LOGIN, LOGIN Name = " + account);
			} else {
				password = PasswordUtil.md5Hex(originPassword);
				// 第二密码
				// 由于绿城OA推送的密码,不包含emm前缀,当登录M2系统登录时,不去掉emm前缀加密,永远无法登录
				// 临时解决方案.搞第二验证密码,第一个不通过,验证第二个
				password2 = DigestUtils.md5Hex(getContentBytes(originPassword, "utf-8"));
			}
			userDto.setUserPhone(account);
			// userDto.setUserStatus(UserStatusEnum.IN_USE.getNo());

			User user = service.selectByDto(userDto);
			if (null != user) {
				String oaUserCode = user.getOaUserCode();
				if (StringUtils.isNotEmpty(oaUserCode)) {
					user = service.loginWithAccountOnly(userDto);
				}
			}

			if (null == user) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage(account));
				return response;
			}
			if (user.getUserStatus().equals(UserStatusEnum.UN_USE.getNo())) {
				response.fail("50000", "账户已被禁用, 请联系管理激活账户");
				return response;
			}

			String userPassword = user.getUserPassword();
			userPassword = userPassword.toUpperCase();
			password = password.toUpperCase();
			if (!password.equals(userPassword)) {
				// 账户密码加密,去掉emm前缀.
				password2 = password2.toUpperCase();
				if (!password2.equals(userPassword)) {
					response.fail("0003", "账户或密码错误");
					return response;
				}
				// response.fail("0003", "密码错误");
				// return response;
			}

			response.setSuccess(Boolean.TRUE);
			response.setEntity(user);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("登陆错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<UserDto> save(UserDto dto) {
		Response<UserDto> response = new Response<UserDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			// 查询账号或者手机号是否重复，如果重复不能新增
			if (dto.getRoleId() == null) {
				response.fail("90000", "请选择角色");
				return response;
			}

			UserDto queryUserDto = new UserDto();
			queryUserDto.setUserPhone(dto.getUserPhone());
			List<User> phoneList = service.selectListByDto(queryUserDto);
			if (null != phoneList && phoneList.size() > 0) {
				response.fail("90000", "手机号已存在");
				return response;
			}
			dto.setUserCode(modelKeyService.next(ModelEnum.USER));
			dto.setUserAccount(dto.getUserPhone());
			UserDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(UserDto dto, boolean uniqueVerification, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			User user = service.selectById(dto.getId());
			if (uniqueVerification) {
				if (null == user) {
					response.fail("90000", "用户不存在");
					return response;
				}
				UserDto queryUserDto = new UserDto();
				if (!user.getUserPhone().equals(dto.getUserPhone())) {
					queryUserDto = new UserDto();
					queryUserDto.setUserPhone(dto.getUserPhone());
					List<User> phoneList = service.selectListByDto(queryUserDto);
					if (null != phoneList && phoneList.size() > 0) {
						response.fail("90000", "手机号已存在");
						return response;
					}
				}
			}

			if (selective) {
				// 非绿城,手机号与账号同步.绿城账号是OA推送而来.修改手机号时,不能修改账号
				if(!MerchantEnum.GREEN_TOWN.getNo().equals(String.valueOf(user.getMerchantId()))){
					dto.setUserAccount(dto.getUserPhone());
				}
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			UserDto mDto = new UserDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<User> findById(Long id) {
		Response<User> response = new Response<User>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			User entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<User> findByDto(UserDto dto) {
		ResponseList<User> response = new ResponseList<User>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<User> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<User> findPageByDto(UserDto dto, Integer begin, Integer row) {
		Page<User> response = new Page<User>();
		response.setPageSize(row);
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}

			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(),
						dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				// 查询非管理员用户
				String dataPermissionSql = dataPermissionArr[1] + " and t.is_admin ='0' ";
				dto.setDataPermission(dataPermissionSql);
			}

			Page<User> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Boolean> changePassword(Long userId, String opwd, String npwd, String qpwd) {
		Response<Boolean> response = new Response<Boolean>();
		if (null == userId) {
			response.fail("90002", "用户不存在");
			return response;
		}
		if (StringUtils.isBlank(opwd)) {
			response.fail("90000", "原密码不能为空");
			return response;
		}
		if (StringUtils.isBlank(npwd) || StringUtils.isBlank(qpwd)) {
			response.fail("90000", "新密码不能为空");
			return response;
		}
		if (!npwd.equals(qpwd)) {
			response.fail("90001", "两次密码不一样");
			return response;
		}
		User user = service.selectById(userId);
		if (null == user) {
			response.fail("90002", "用户不存在");
			return response;
		}
		String password2 = "";
		String originPassword = opwd;
		String md5npwd = PasswordUtil.md5Hex(originPassword);
		if (!md5npwd.equals(user.getUserPassword())) {
			// 第二密码
			// 由于绿城OA推送的密码,不包含emm前缀,当登录M2系统登录时,不去掉emm前缀加密,永远无法登录
			// 临时解决方案.搞第二验证密码,第一个不通过,验证第二个
			password2 = DigestUtils.md5Hex(getContentBytes(originPassword, "utf-8"));
			if (!password2.equals(user.getUserPassword())) {
				response.fail("90002", "原密码错误");
				return response;
			}
		}
		UserDto userDto = new UserDto();
		userDto.setId(userId);
		userDto.setUserPassword(PasswordUtil.md5Hex(npwd));
		userDto.setUpdateTime(new Date());
		userDto.setUpdateUserId(userId);
		int count = service.update(userDto);
		if (count < 0) {
			response.fail("90003", "修改失败");
			return response;
		}
		response.success(Boolean.TRUE);
		return response;
	}

	@Override
	public ResponseList<User> userByProjectIdForGroup(Long projectId, String resourcesCode, Long isList, Long userId) {
		ResponseList<User> response = new ResponseList<User>();
		try {
			User user = service.selectById(userId);
			String projectIdSql = null;
			String userIdSql = null;
			String mtIdSql = null;
			// 1、查询用户角色
			// 2、根据角色获取角色相关信息
			// 2.1、无,无数据返回
			// 2.2、个人,返回自身信息
			// 2.3、项目组,用户所在的项目的所有成员
			// 2.4、销售组,用户所在所有销售组的成员
			// 2.5、所有经纪人
			if (isList != null && isList == 1) {
				String roleDataAuthorityValue = dataPermissionService.roleDataAuthorityValue(userId, resourcesCode);
				if (roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_00.getNo())) {
					response.fail(ResponseCode.NO_DATA_FOUND.getCode(),
							ResponseCode.NO_DATA_FOUND.formatMessage("权限查询"));
					return response;
				} else if (roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_01.getNo())
						|| roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_05.getNo())) {
					userIdSql = " and t.id = " + userId;
				} else if (roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_02.getNo())) {
					// 项目组权限
					// 1、查询用户所在的所有销售组
					SalesGroupUserDto sguDto = new SalesGroupUserDto();
					sguDto.setUserId(userId);
					sguDto.setMerchantId(user.getMerchantId());
					sguDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					List<SalesGroupUser> sguList = salesGroupUserService.selectListByDto(sguDto);
					Set<Long> sgIdSet = new HashSet<Long>();
					if (null != sguList) {
						for (SalesGroupUser sgu : sguList) {
							sgIdSet.add(sgu.getSalesGroupId());
						}
					} else {
						response.fail(ResponseCode.NO_DATA_FOUND.getCode(),
								ResponseCode.NO_DATA_FOUND.formatMessage("用户无项目组"));
						return response;
					}
					// 2、获取销售组组下的所有项目ID
					Set<String> projectIdSet = new HashSet<String>();
					for (Long sgId : sgIdSet) {
						SalesGroup sg = salesGroupService.selectById(sgId);
						projectIdSet.add(String.valueOf(sg.getProjectId()));
					}
					// 4、组装项目参数
					Iterator<String> it = projectIdSet.iterator();
					if (it.hasNext()) {
						StringBuffer sb = new StringBuffer();
						sb.append(" and p.id in(");
						while (it.hasNext()) {
							sb.append(it.next());
							if (it.hasNext()) {
								sb.append(",");
							}
						}
						sb.append(")");
						projectIdSql = sb.toString();
					}
				} else if (roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_03.getNo())) {
					// 本部无此数据权限
				} else if (roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_99.getNo())) {
					// 全部,不参与条件拼装
				} else if (roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_04.getNo())) {
					// 销售组
					SalesGroupUserDto salesGroupUserDto = new SalesGroupUserDto();
					salesGroupUserDto.setUserId(userId);
					salesGroupUserDto.setStatus("0");
					salesGroupUserDto.setMerchantId(user.getMerchantId());
					List<SalesGroupUser> salesGroupUserList = salesGroupUserService.selectListByDto(salesGroupUserDto);
					if (salesGroupUserList != null && salesGroupUserList.size() > 0) {
						StringBuffer sb = new StringBuffer();
						sb.append(" and mt.id in(");
						for (int i = 0; i < salesGroupUserList.size(); i++) {
							sb.append(salesGroupUserList.get(i).getSalesGroupId());
							if (i < salesGroupUserList.size() - 1)
								sb.append(",");
						}
						sb.append(")");
						mtIdSql = sb.toString();
					}
				}
			}

			List<User> list = service.userByProjectIdForGroup(projectId, userIdSql, mtIdSql, projectIdSql,
					String.valueOf(user.getMerchantId()));
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	public ResponseList<User> findDataPermissionByDto(UserDto dto, Boolean isDataPermission) {
		ResponseList<User> response = new ResponseList<User>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			// 数据权限
			if (SysConstants.openDataPermission && isDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(),
						dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					response.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				dto.setDataPermission(dataPermissionArr[1]);
			}
			List<User> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<ResponseOrg> orgData(OrgOaDataVo orgData, User user) {
		Response<ResponseOrg> response = new Response<ResponseOrg>();
		try {
			// 同步公司
			if (orgData.getSubCompany() != null && orgData.getSubCompany().size() > 0) {
				for (SubCompany company : orgData.getSubCompany()) {
					ResponseOrg res = vaildData(company);
					if (res != null) {
						response.setSuccess(false);
						response.setEntity(res);
						return response;
					} else {

						DepartmentDto departmentObj = new DepartmentDto();
						departmentObj.setDepartmentCode(company.getSubcompanyCode());
						departmentObj.setDepartmentName(company.getSubcompanyname());
						departmentObj.setSubcompanyCode(company.getSupsubcomCode());
						departmentObj.setDepartmentcategory(company.getSubcompanyCategory());
						if (!company.getSupsubcomCode().equals("LCDF001")) {
							departmentObj.setParentId(getDepartmentId(company.getSupsubcomCode()));
						} else {
							departmentObj.setParentId(-1L);
						}
						setDepartmentDto(user, departmentObj);
					}
				}
			}
			// 同步部门
			if (orgData.getHrmDepartment() != null && orgData.getHrmDepartment().size() > 0) {
				for (HrmDepartment department : orgData.getHrmDepartment()) {
					ResponseOrg res = vaildData(department);
					if (res != null) {
						response.setSuccess(false);
						response.setEntity(res);
						return response;
					} else {
						// 新增或者修改部门
						DepartmentDto departmentObj = new DepartmentDto();
						departmentObj.setDepartmentCode(department.getDepartmentCode());
						departmentObj.setDepartmentName(department.getDepartmentname());
						departmentObj.setSubcompanyCode(department.getSubcompanyCode());
						departmentObj.setDepartmentcategory(department.getHrmdepartmentCategory());
						departmentObj.setParentId(getDepartmentId(department.getSubcompanyCode()));
						setDepartmentDto(user, departmentObj);
					}
				}
			}

			// 同步员工
			if (orgData.getHrmResource() != null && orgData.getHrmResource().size() > 0) {
				for (HrmResource resource : orgData.getHrmResource()) {
					if ("1".equals(resource.getAccounttype())) {
						continue;
					}
					ResponseOrg res = vaildData(resource);
					if (res != null) {
						response.setSuccess(false);
						response.setEntity(res);
						return response;
					} else {
						UserDto addUser = new UserDto();
						try {
							UserDto userDto = new UserDto();
							userDto.setOaUserCode(resource.getHrmresourceId());
							User us = service.selectByDto(userDto);

							addUser.setOaUserCode(resource.getHrmresourceId());
							addUser.setUserName(resource.getLastname());
							addUser.setSex(resource.getSex());
							addUser.setEmail(resource.getEmail());
							addUser.setUserAccount(resource.getLoginid());
							addUser.setUserPhone(resource.getMobile());
							addUser.setUserPassword(resource.getPassword());
							if (resource.getStatus().equals("0") || resource.getStatus().equals("1")
									|| resource.getStatus().equals("2") || resource.getStatus().equals("3")) {
								addUser.setUserStatus(UserStatusEnum.IN_USE.getNo());
							} else {
								addUser.setUserStatus(UserStatusEnum.UN_USE.getNo());
							}
						/*
						if(StringUtils.isNotBlank(resource.getUsericon())) {
							JSONObject result = getUrlByBase64(resource.getUsericon());
							String postResult = result.getString("result");
							if("1".equals(postResult)) {
								addUser.setHeadPic(result.getString("url"));
							} else {
								logger.error("OA同步用户头像失败");
							}
						}
						*/
							addUser.setPosition(resource.getJobtitle());
							addUser.setUserDepartmentId(getDepartmentId(resource.getDepartmentCode()));
							addUser.setIsAdmin("0");
							addUser.setMerchantId(user.getMerchantId());
							addUser.setCreateTime(new Date());
							addUser.setCreateUserId(user.getId());
							addUser.setUpdateTime(new Date());
							addUser.setUpdateUserId(user.getId());
							addUser.setCompanyCode(resource.getSubcompanyCode());
							addUser.setDelFlag(DelFlagEnum.UNDEL.getNo());
							if (us == null) {
								addUser.setUserCode(modelKeyService.next(ModelEnum.USER));
								service.create(addUser);
							} else {
								addUser.setId(us.getId());
								service.update(addUser);
							}
						}catch (Exception ex){
							logger.error("同步人员错误,错误人员信息:" + JSON.toJSONString(addUser), ex);
						}
					}
				}
			}
			ResponseOrg res = new ResponseOrg();
			response.setSuccess(false);
			res.setCode("200");
			res.setDesc("数据同步成功");
			response.setEntity(res);
		} catch (Exception e) {
			logger.error("同步数据错误：{}", e);
			ResponseOrg res = new ResponseOrg();
			response.setSuccess(false);
			res.setCode("500");
			res.setDesc("接口异常,请联系管理员");
			response.setEntity(res);
		}
		return response;
	}
	
	//上传头像
	@Value("${file.serviceUrl}")
	private String fileUploadUrl;
	public JSONObject getUrlByBase64(String headPic) {
		//保存更新图片
		String imgName = SequencesGenerator.getUUID("IMG") + ImageTypeEnum.png;
		String result = FileUploadPorxyUtil.appPost(fileUploadUrl, headPic, imgName);
		JSONObject resultJson=JSON.parseObject(result);
		return resultJson;
	}

	public void setDepartmentDto(User user, DepartmentDto departmentObj) {
		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		departmentDto.setDepartmentCode(departmentObj.getDepartmentCode());
		ResponseList<Department> responseList = departmentServiceFacade.findByDto(departmentDto);
		departmentObj.setCanceled("0");
		departmentObj.setUpdateTime(new Date());
		departmentObj.setDelFlag(DelFlagEnum.UNDEL.getNo());
		departmentObj.setCreateUserId(user.getId());
		departmentObj.setUpdateUserId(user.getId());
		departmentObj.setMerchantId(user.getMerchantId());
		if (responseList.isSuccess() && responseList.getEntity() != null && responseList.getEntity().size() > 0) {
			// 修改
			departmentObj.setId(responseList.getEntity().get(0).getId());
			departmentServiceFacade.updateByPrimaryKey(departmentObj, true);
		} else {
			departmentObj.setCreateTime(new Date());
			// 新增
			departmentServiceFacade.save(departmentObj);
		}
	}

	public ResponseOrg vaildData(Object obj) {
		ResponseOrg org = new ResponseOrg();
		Validator validator = new Validator();
		List<ConstraintViolation> ret = validator.validate(obj);
		if (ret != null && ret.size() > 0) {
			org.setCode("500");
			org.setDesc("参数" + ret.get(0).getMessage());
			return org;
		}
		return null;
	}

	public Long getDepartmentId(String departmentCode) {
		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		departmentDto.setDepartmentCode(departmentCode);
		ResponseList<Department> responseList = departmentServiceFacade.findByDto(departmentDto);
		if (responseList.isSuccess() && responseList.getEntity() != null && responseList.getEntity().size() > 0) {
			return responseList.getEntity().get(0).getId();
		}
		return null;
	}

	private static byte[] getContentBytes(String content, String charset) {
		if (charset == null || "".equals(charset)) {
			return content.getBytes();
		}
		try {
			return content.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
		}
	}

	@Override
	public Response<String> hotFixUserCode(List<OaUserExcelDto> userCode) {
		StringBuffer sb = new StringBuffer();
		int i = 1;
		Response<String> response = new Response<String>();
		try {
			for (OaUserExcelDto user : userCode) {
				if (!StringUtils.isEmpty(user.getOldOaUserCode())) {
					UserDto dto = new UserDto();
					dto.setOaUserCode(user.getOldOaUserCode());
					User queryUserDto = service.selectByDto(dto);
					if (queryUserDto != null) {
						UserDto updateUser = new UserDto();
						updateUser.setId(queryUserDto.getId());
						updateUser.setOaUserCode(user.getNewOaUserCode());
						int count = service.update(updateUser);
						if (count > 0) {
							i++;
						}
					} else {
						sb.append(",用户编码" + user.getOldOaUserCode() + "不存在!");
					}
				}
			}
			response.setEntity("更新成功:" + i + "条" + sb.toString());
		} catch (Exception e) {
			logger.error("更新错误", e);
		}
		return response;
	}

	/**
	 * 根据客户手机号查询经纪人列表
	 */
	@Override
	public AgentListResDto agentListByCustomerPhone(QueryAgentListByCustomerPhoneReqDto reqDto) {
		AgentListResDto resDto = new AgentListResDto();

		String phone = reqDto.getCustomerPhone();
		if (StringUtils.isBlank(phone)) {
			resDto.setErrorCode("0000");
			resDto.setErrorMsg("客户电话不能为空");
			resDto.setResult("0");
		}

		List<AgentRes> list = service.agentListByCustomerPhone(phone, reqDto.getProjectCode());
		if (list == null) {
			list = new ArrayList<AgentRes>();
		}
		resDto.setAgentList(list);
		resDto.setResult("1");
		return resDto;
	}
}
